package com.z.redis.command.impl.set;

import com.z.redis.RedisCore;
import com.z.redis.command.CommandType;
import com.z.redis.command.WriteCommand;
import com.z.redis.datatype.BytesWrapper;
import com.z.redis.datatype.RedisSet;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import com.z.redis.resp.RespInt;
import io.netty.channel.ChannelHandlerContext;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 移除集合中的一个或者多个元素
 */
public class Srem implements WriteCommand {
    private BytesWrapper key;
    private List<BytesWrapper> members;

    @Override
    public CommandType type(){
        return CommandType.srem;
    }

    @Override
    public void setContent(Resp[] array){
        key = ((BulkString) array[1]).getContent();
        members = Stream.of(array)
                .skip(2)
                .map(resp -> ((BulkString) resp).getContent())
                .collect(Collectors.toList());
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        RedisSet redisSet = (RedisSet) redisCore.get(key);
        int srem = redisSet.srem(members);
        ctx.writeAndFlush(new RespInt(srem));
    }

    @Override
    public void handle(RedisCore redisCore){
        RedisSet redisSet = (RedisSet) redisCore.get(key);
        int srem = redisSet.srem(members);
    }
}
